package com.hopes.bizz.protocol.hj212.activemq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Session;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author daijie
 * @version 1.0
 * @date 2023/5/24 16:58
 * @Description:
 */
@Slf4j
@Configuration
public class ActiveMqStore implements CommandLineRunner {

    @Autowired
    private ConnectionFactory activeMqConnectionFactory;
    private Connection connection = null;
    private Session session = null;
    ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run(String... args) throws Exception {
        connection = activeMqConnectionFactory.createConnection();
        connection.start();
        log.info("ActiveMq connection创建成功");
    }

    @PreDestroy
    private void destroy() throws JMSException {
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

    public Session getSession() {
        if (session != null) {
            return session;
        }
        lock.lock();
        try {
            if (session != null) {
                return session;
            }
            while (connection == null) {
                Thread.sleep(500);
            }
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            log.info("ActiveMq session创建成功");
        } catch (JMSException e) {
            log.error("session创建失败,错误码={},原因={}", e.getErrorCode(), e.getMessage());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
        return session;
    }

    public void createNewSession() {
        session = null;
        lock.lock();
        try {
            if (session != null) {
                return;
            }
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            log.info("ActiveMq 新session创建成功");
        } catch (JMSException e) {
            log.error("尝试创建新session失败,错误码={},原因={}", e.getErrorCode(), e.getMessage());
        }finally {
            lock.unlock();
        }
    }
}
